﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using Microsoft.Win32;
using System.Reflection;

namespace BingImages
{
    public partial class mainForm : Form
    {
        private Settings _settings;
        public Settings settings
        {
            get { return this._settings; }
        }
        private Folder _folder;
        public Folder folder
        {
            get { return this._folder; }
        }
                
        private Copy _copy;
        private StreamBing _streamBing;
        private MainDraw _draw;
        private ToolTip _ttipBrowse;
        private ToolTip _ttipWallpaperScroll;
        private ToolTip _ttipConfirm;
        private ToolTip _ttipCancel;
        private ToolTip _ttipSignal;
        private int _oldPictureIndex = 0;
        private bool _setFolder = false;
        private bool _setValue = false;

        public mainForm()
        {
            InitializeComponent();

            // ------------ DEBUT TOOLTIP ------------ //
            this._ttipBrowse = new ToolTip();
            this._ttipBrowse.SetToolTip(btnBrowse, "Parcourir");

            this._ttipWallpaperScroll = new ToolTip();
            this._ttipWallpaperScroll.SetToolTip(btnWallpaperScroll, "Thème");

            this._ttipConfirm = new ToolTip();
            this._ttipConfirm.SetToolTip(btnConfirm, "Valider");

            this._ttipCancel = new ToolTip();
            this._ttipCancel.SetToolTip(btnCancel, "Réduire");

            this._ttipSignal = new ToolTip();
            // ------------ FIN TOOLTIP ------------ //

            this._settings = new Settings();
            this._folder = new Folder();
            this._copy = new Copy();
            this._streamBing = new StreamBing(this._settings.wallpaperScroll);
            this._draw = new MainDraw(this);
            this.init();
            this._setValue = true;
        }

        private void init()
        {
            this._streamBing.getPicture();
            this._folder.deleteFiles("wallpaper", "*.jpg");

            // ------------ DEBUT INITIALISATION TEXTBOX (tbxPath) ------------ //
            if (this._settings.pathExist())
            {
                this.tbxPath.Text = this._settings.path;
            }
            else
            {
                this.tbxPath.Text = "-- Aucun dossier sélectionné --";
            }
            // ------------ FIN INITIALISATION TEXTBOX (tbxPath) ------------ //

            // ------------ DEBUT INITIALISATION CHECKBOX & BUTTON ------------ //
            if (this._settings.pathExist())
            {
                this.ckbxArchivePicture.Enabled = true;
                this.ckbxArchiveDelete.Enabled = true;
                this.btnWallpaperScroll.Enabled = true;
            }
            // ------------ FIN INITIALISATION CHECKBOX & BUTTON ------------ //

            // ------------ DEBUT INITIALISATION CHECKBOX (cbxStart) ------------ //
            if (this._settings.start == "True")
            {
                this.ckbxStart.Checked = true;
                this.ckbxStart.Image = Properties.Resources.on;
            }
            // ------------ FIN INITIALISATION CHECKBOX (cbxStart) ------------ //

            // ------------ DEBUT INITIALISATION CHECKBOX (cbxArchivePicture) ------------ //
            if (this._settings.archivePicture == "True")
            {
                this.ckbxArchivePicture.Checked = true;
                this.ckbxArchivePicture.Image = Properties.Resources.on;
                this.setPbxSignal();
            }
            // ------------ FIN INITIALISATION CHECKBOX (cbxArchivePicture) ------------ //

            // ------------ DEBUT INITIALISATION CHECKBOX (cbxArchiveDelete) ------------ //
            if (this._settings.archiveDelete == "True")
            {
                this.ckbxArchiveDelete.Checked = true;
                this.ckbxArchiveDelete.Image = Properties.Resources.on;
            }
            // ------------ FIN INITIALISATION CHECKBOX (cbxArchiveDelete) ------------ //

            // ------------ DEBUT MULTIPLE FONDS D'ECRAN ------------ //
            if (!string.IsNullOrEmpty(this._settings.wallpaperScroll))
            {
                Theme.setTheme(this._settings.wallpaperScroll, this._settings.timeInterval);
            }
            // ------------ FIN MULTIPLE FONDS D'ECRAN ------------ //

            // ------------ DEBUT INITIALISATION COMBOBOX (cbxNumberImage) ------------ //
            if (!string.IsNullOrEmpty(this._settings.numberPicture))
            {
                this.cbxNumberPicture.SelectedIndex = int.Parse(this._settings.numberPicture);
            }
            else
            {
                this.cbxNumberPicture.SelectedIndex = 0;
            }

            this._oldPictureIndex = this.cbxNumberPicture.SelectedIndex;
            // ------------ FIN INITIALISATION COMBOBOX (cbxNumberImage) ------------ //

            this.gbxPicture.Text = "Images (" + DateTime.Now.ToString("MM.yyyy") + ")";
        }

        private void newCopy()
        {
            this._copy.copyFiles(this._folder.last, this._settings.path, "*.png");
            Archive.setArchive(this._settings.archivePicture, this._settings.archiveDelete, this._settings.path);
            this._copy.copyPicture(this._settings.path, this._folder.wallpaperPath, "*.png", new Size(86, 75));
            this._copy.copyPicture(this._folder.last, this._folder.wallpaperPath, "*.png", new Size(86, 75));
        }

        private void setPbxSignal()
        {
            int totalDays = 0;
            int percent = 0;
            string archivingDay = "";

            if (this.pbxSignal != null)
            {
                this.pbxSignal.BackgroundImage.Dispose();
                this.pbxSignal.BackgroundImage = null;
            }

            totalDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
            percent = DateTime.Now.Day * 100 / totalDays;

            if (percent > 0 && percent < 19)
            {
                this.pbxSignal.BackgroundImage = Properties.Resources.load1;
            }
            else if (percent >= 19 && percent < 48)
            {
                this.pbxSignal.BackgroundImage = Properties.Resources.load2;
            }
            else if (percent >= 48 && percent < 80)
            {
                this.pbxSignal.BackgroundImage = Properties.Resources.load3;
            }
            else
            {
                this.pbxSignal.BackgroundImage = Properties.Resources.load4;
            }

            archivingDay = (totalDays - DateTime.Now.Day + 1).ToString();
            this._ttipSignal.SetToolTip(this.pbxSignal, archivingDay + " jours");
            this.pbxSignal.Visible = true;
        }

        private void editSettings()
        {
            // ------------ DEBUT MODIFICATIONS FICHIER CONFIGURATION ------------ //
            RegistryKey myRegistryKey;

            if (this._setFolder == true && Directory.Exists(this.browseFolder.SelectedPath))
            {
                this._settings.save("path", this.browseFolder.SelectedPath);
            }

            if (this.ckbxStart.Checked)
            {
                // ------------ DEBUT CHEMIN APPLICATION ------------ //
                string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
                string appName = AppDomain.CurrentDomain.FriendlyName;
                string appPath = appDirectory + "\\" + appName;
                // ------------ FIN CHEMIN APPLICATION ------------ //

                myRegistryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\windows\CurrentVersion\run\", true);
                myRegistryKey.SetValue("BingImages", appPath, RegistryValueKind.String);
                myRegistryKey.Close();
            }
            else
            {
                myRegistryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\windows\CurrentVersion\run\", true);
                if (myRegistryKey.GetValue("BingImages") != null)
                {
                    myRegistryKey.DeleteValue("BingImages");
                }
                myRegistryKey.Close();
            }

            this._settings.save("start", this.ckbxStart.Checked.ToString());
            this._settings.save("archiveImage", this.ckbxArchivePicture.Checked.ToString());
            this._settings.save("archiveDelete", this.ckbxArchiveDelete.Checked.ToString());

            int val_index = cbxNumberPicture.SelectedIndex;

            if (val_index > -1)
            {
                this._settings.save("numberPicture", val_index.ToString());
            }
            // ------------ FIN MODIFICATIONS FICHIER CONFIGURATION ------------ //

            this._settings = new Settings();
        }

        private void clear(CheckBox ckbx)
        {
            if (ckbx != null)
            {
                ckbx.Image.Dispose();
                ckbx.Image = null;
            }
        }

        private void ckbxImage(CheckBox ckbx)
        {
            if(ckbx.Checked)
            {
                ckbx.Image = Properties.Resources.on;
            }
            else
            {
                ckbx.Image = Properties.Resources.off;
            }
        }

        public ComboBox getCbxNumberPicture()
        {
            return this.cbxNumberPicture;
        }

        public FlowLayoutPanel getFlpPicture()
        {
            return this.flpPicture;
        }

        public Settings getSettings()
        {
            return this._settings;
        }

        #region EVENTS
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
            {
                this.notifyIcon.Visible = true;

                this.Hide();
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            
            if (this.browseFolder.ShowDialog(this) == DialogResult.OK)
            {
                this.tbxPath.Text = browseFolder.SelectedPath;
                this.btnConfirm.Enabled = true;
                this._setFolder = true;
            }
        }

        private void ckbxStart_CheckedChanged(object sender, EventArgs e)
        {
            this.clear(this.ckbxStart);
            this.ckbxImage(this.ckbxStart);
            this.btnConfirm.Enabled = true;
        }

        private void ckbxArchivePicture_CheckedChanged(object sender, EventArgs e)
        {
            this.clear(this.ckbxArchivePicture);
            this.ckbxImage(this.ckbxArchivePicture);
            this.btnConfirm.Enabled = true;

            if (this.ckbxArchivePicture.Checked)
            {
                this.setPbxSignal();
            }
            else
            {
                this.ckbxArchiveDelete.Checked = false;
                this.pbxSignal.Visible = false;
            }
        }

        private void ckbxArchiveDelete_CheckedChanged(object sender, EventArgs e)
        {
            this.clear(this.ckbxArchiveDelete);
            this.ckbxImage(this.ckbxArchiveDelete);
            this.btnConfirm.Enabled = true;

            if (this.ckbxArchiveDelete.Checked)
            {
                this.ckbxArchivePicture.Checked = true;
            }
        }

        private void btnWallpaperScroll_Click(object sender, EventArgs e)
        {
            themeForm themeForm = new themeForm();
            themeForm.ShowDialog();
            
            this._folder.deleteFiles("temp", "*.jpg");
            this._folder.deleteFiles("temp", "*.png");
        }

        private void cbxNumberPicture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!this._setValue)
            {
                this.newCopy();
                this._draw.setDraw();
            }

            if(this.cbxNumberPicture.SelectedIndex != this._oldPictureIndex)
            {
                if (this.btnConfirm.Enabled != true)
                {
                    this.btnConfirm.Enabled = true;
                }

                this._draw.setDraw();
            }

            this._oldPictureIndex = this.cbxNumberPicture.SelectedIndex;
            this.flpPicture.Focus();
        }

        private void flpPicture_MouseEnter(object sender, EventArgs e)
        {
            this.flpPicture.Focus();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.editSettings();
            this._draw.init();
            this._folder.deleteFiles("wallpaper", "*.jpg");
            this.newCopy();
            this._draw.setDraw();
            if (this._settings.pathExist())
            {
                this.ckbxArchivePicture.Enabled = true;
                this.ckbxArchiveDelete.Enabled = true;
                this.btnWallpaperScroll.Enabled = true;
            }
            this.btnConfirm.Enabled = false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            this.notifyIcon.Visible = false;
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.flpPicture.AutoScroll = true;
            this.flpPicture.Focus();
        }

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion
    }
}
